import os
import json
import time
import requests
import pandas as pd

headers = {
    'Host': 'music.163.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}

def get_comments(song_id, song_name, artist, output_dir):
    """
    获取评论信息并保存到文件夹中
    """
    filename = f"{output_dir}/{song_id}_{song_name}_{artist}.csv"
    comment_counts = [0] * 12  # 统计每两个小时内的评论数

    for page in range(0, 10000, 100):
        url = f'https://music.163.com/api/v1/resource/comments/R_SO_4_{song_id}?limit=20&offset={page}'
        response = requests.get(url=url, headers=headers, proxies={"http": None, "https": None})
        result = json.loads(response.text)

        if 'comments' not in result:
            break

        items = result['comments']
        for item in items:
            timestamp = int(str(item['time'])[:10])
            date = time.localtime(timestamp)
            hour = date.tm_hour
            time_slot = hour // 2  # 统计每两小时的评论数
            comment_counts[time_slot] += 1

    # 使用pandas保存统计结果到CSV文件
    time_slots = [f"{i*2:02}:00-{(i*2+2)%24:02}:00" for i in range(12)]
    df = pd.DataFrame({
        "Time Slot": time_slots,
        "Comment Count": comment_counts
    })
    df.to_csv(filename, index=False, encoding='utf-8-sig')

def main():
    music_data = pd.read_csv('网易云评论分析zzz\musicData.csv')
    output_dir = "comments"
    os.makedirs(output_dir, exist_ok=True)

    for _, row in music_data.iterrows():
        song_id = row['id']
        song_name = row['title']
        artist = row['artist']
        get_comments(song_id, song_name, artist, output_dir)

if __name__ == '__main__':
    main()
